package br.uece.laconi.tac.fuzzy;

import java.text.DecimalFormat;

import br.uece.laconi.tac.fuzzy.functions.GenericFunction;
import br.uece.laconi.tac.fuzzy.functions.LinearFunction;


public class TriangleFuzzyNumber extends FuzzyNumber {
	public float center;
	public float leftSpread;
	public float rightSpread;
	
	public TriangleFuzzyNumber(float center, float leftSpread, float rightSpread) {
		this (new float[]{center - leftSpread, center, center + rightSpread});
		this.center = center;
		this.leftSpread = leftSpread;
		this.rightSpread = rightSpread;
	}
	
	public TriangleFuzzyNumber(final float[] trianglePoints) {
		super(new GenericFunction() {
			public Float calculate(float[] var) {
				float x = var[0];
				float result = 0f;
				LinearFunction func = new LinearFunction();
				
				if (x <= trianglePoints[0] || x >= trianglePoints[2]) {
					result = 0f;
				}
				else if (x <= trianglePoints[1]) {
					func.autoMake(trianglePoints[0], 0, trianglePoints[1], 1);
					result = func.calculate(x);  
				}
				else if (x > trianglePoints[1]) {
					func.autoMake(trianglePoints[1], 1, trianglePoints[2], 0);
					result = func.calculate(x);  
				}
				return result;
			}
		});
		super.setInterval(trianglePoints[0], trianglePoints[2]);
	}

	@Override
	public FuzzyNumber dividedby(FuzzyNumber num) {
		if (num instanceof CrispFuzzyNumber) {
			CrispFuzzyNumber c = (CrispFuzzyNumber) num;
			float d = c.value;
			return new TriangleFuzzyNumber(center/d, leftSpread/d, rightSpread/d);
		}
		return null;
	}

	@Override
	public FuzzyNumber minus(FuzzyNumber num) {
		if (num instanceof TriangleFuzzyNumber) {
			TriangleFuzzyNumber t = (TriangleFuzzyNumber) num;
			return new TriangleFuzzyNumber(center - t.center, leftSpread - t.leftSpread, rightSpread - t.rightSpread);
		}
		return null;
	}

	@Override
	public FuzzyNumber plus(FuzzyNumber num) {
		if (num instanceof TriangleFuzzyNumber) {
			TriangleFuzzyNumber t = (TriangleFuzzyNumber) num;
			return new TriangleFuzzyNumber(center + t.center, leftSpread + t.leftSpread, rightSpread + t.rightSpread);
		}
		return null;
	}

	@Override
	public FuzzyNumber times(FuzzyNumber num) {
		if (num instanceof CrispFuzzyNumber) {
			CrispFuzzyNumber c = (CrispFuzzyNumber) num;
			float d = c.value;
			return new TriangleFuzzyNumber(center*d, leftSpread*d, rightSpread*d);
		}
		if (num instanceof TriangleFuzzyNumber) {
			TriangleFuzzyNumber t = (TriangleFuzzyNumber) num;
			return new TriangleFuzzyNumber(this.center * t.center, this.center
					* t.leftSpread + t.center * this.leftSpread
					- this.leftSpread * t.leftSpread, this.center
					* t.rightSpread + t.center * this.rightSpread
					+ this.rightSpread * t.rightSpread);
		}
		return null;
	}
	

	public String toString() {
		DecimalFormat df = new DecimalFormat("#.##");
		return "("+df.format(this.center)+","+this.leftSpread +","+this.rightSpread+")";
	}
}
